<template>
	<view class="columnbox content">
		<view class="top-box">共{{list.length}}件商品</view>
		<view class="rowbox wdh-100 spb als one-goods" v-for="(item,index) in list" :key='index'>
			<image :src="item.images.split(',')[0]" mode="aspectFill" class="goods-img"></image>
			<view class="columnbox als goods-info">
				<view class="type-name">{{item.name}}
				</view>
				<view class="changjia">{{item.changjia}} </view>
				<view class="changjia">{{item.guige}}*{{item.danwei}} </view>
				<view class="rowbox wdh-100 spb" style="margin-top: 10rpx;">
					<view class="price">¥{{item.price}} </view>
					<view class="rowbox">
						<template v-if="item.num>0">
							<view @click="minusNum(item)" class="rowbox def-bgcol add-box-minus">
								<u-icon name="minus" color="#00b6b2" size="24rpx"></u-icon>
							</view>
							<view class="goods-num">{{item.num}}</view>
						</template>
						<view class="rowbox def-bgcol add-box" @click="addNum(item)">
							<u-icon name="plus" color="#fff" size="24rpx"></u-icon>
						</view>
					</view>
				</view>
			</view>
		</view>
		<view class="wdh-100" style="height: 150rpx; "></view>
		<view class="rowbox wdh-100 spb submit-box">
			<view class="totalPrice">合计: <text>¥{{totalPrice}}</text> </view>
			<view class="def-bgcol rowbox submit-btn" @click="comfirmAdd">确认推荐</view>
		</view>
	</view>
</template>

<script>
	// 环信即时通讯
	import SDK from 'js_sdk/easemob-im-uni-app/Easemob-chat';
	// 实例化 SDK 对象
	const WebIM = wx.WebIM = SDK;
	export default {
		data() {
			return {
				reconnectcount: 0,
				list: [],
				totalPrice: 0,
				submitfalg: false,
				id: '',
				logo: '',
				name: '',
				userid:0
			};
		},
		onLoad(options) {
			if (options.id) {
				this.id = options.id
				this.logo = options.logo
				this.name = options.name
				this.userid=options.userid
			}
			this.list = JSON.parse(options.list)
			this.list.forEach(v => {
				this.totalPrice += v.price * 1
			})
		},
		methods: {
			minusNum(v) {
				v.num--
				this.totalPrice -= v.price * 1
			},
			addNum(v) {
				v.num++
				this.totalPrice += v.price * 1
			},

			getSelectList() {
				return new Promise(resolve => {
					let servetypeids = []
					this.list.forEach(res => {
						if (res.num > 0) {
							servetypeids.push({
								goodid: res.id * 1,
								num: res.num * 1,
								price: res.price * 1,
							})
						}
					})
					resolve(servetypeids)
				})
			},
			async comfirmAdd() {
				let servetypeids = await this.getSelectList()
				if (servetypeids.length == 0) {
					uni.showToast({
						title: '请选择商品',
						icon: 'none'
					})
					return false
				}
				if (!this.submitfalg) {
					this.submitfalg = true
					uni.showLoading({
						title: '正在保存'
					})
					this.$req.post('/doctor/goodcartadd', {
						doctorid: uni.getStorageSync('uid'),
						parameter: JSON.stringify(servetypeids),
					}).then(res => {
						this.submitfalg = false
						if (this.id == '') {
							uni.hideLoading()
							uni.redirectTo({
								url: '/packageA/goods/ewm?url=' + res.data.erweima + '&data=' + res.data
									.data
							})
						} else {
							this.bindOrder(res.data.data)
						}
					})
				}
			},
			bindOrder(id) {
				this.$req.post('/user/goodorderbd', {
					id: id * 1,
					userid: this.userid * 1
				}).then(res => {
					this.sendMessage(id, 6)
				})
			},
			// sendMessage(id) {
			//     console.log(this.logo)
			//     getApp().globalData.chatSocket.send({
			//         data: JSON.stringify({
			//             "receiveid": this.id * 1,
			//             "content": id + '',
			//             "classify": 6,
			//         }),
			//         success: res => {
			//             console.log('发送成功', res)
			//             setTimeout(() => {
			//                 // 将当前发送信息 添加到消息列表。
			//                 getApp().globalData.chatDetailNew = {
			//                     friendsid: this.id * 1,
			//                     content: id + '',
			//                     classify: 6,
			//                     logo: this.logo,
			//                     last_id: '',
			//                     name: this.name,
			//                     unread_cnt: 1,
			//                     addtime: Date.parse(new Date()) / 1000,
			//                     userid: '',
			//                 }
			//                 uni.hideLoading()
			//                 let pages = getCurrentPages(); //获取所有页面栈实例列表
			//                 let nowPage = pages[pages.length - 1]; //当前页页面实例
			//                 let prevPage = pages[pages.length - 2]; //上一页页面实例
			//                 prevPage.$vm.refreshflag = true
			//                 uni.navigateBack()
			//             }, 500);
			//         },
			//         fail: (err) => {
			//             getApp().globalData.chatSocket = uni.connectSocket({
			//                 url: 'wss://zhongyi.weizi000.cn/chat/sChat/' + uni.getStorageSync(
			//                     'userinfo').memberid,
			//                 success: (res) => {
			//                     console.log('连接成功111', res)
			//                     this.sendMessage(id)
			//                 },
			//                 fail: (err) => {
			//                     if (this.reconnectcount < 10) {
			//                         this.reconnectcount++
			//                         this.sendMessage(id)
			//                     }
			//                     console.log('链接失败', err)
			//                 }
			//             })
			//         }
			//     });
			// },


			sendMessage(content, classify) {

				let infocontent = {
					classify: classify,
					content: '商品推荐',
					otherid: parseInt(content), //开方ID
					name: this.name,
					chatroomheadpic: this.logo,
				}
				let option = {
					type: "txt",
					msg: JSON.stringify(infocontent),
					to: this.id + "",
					chatType: "singleChat",
				};
				let msg = WebIM.message.create(option);
				getApp().globalData.conn.send(msg).then(res => {
					console.log("=========Send message success");
					// uni.hideLoading()
					this.$store.dispatch('actionsHandleNewChatChange', {
						msg: JSON.stringify(infocontent),
						from: this.id + '',
						time: Date.parse(new Date),
						chatdetailflag: true,
						serverMsgId: res.serverMsgId
					});
					uni.navigateBack()
				}).catch((e) => {
					console.log("==============Send message fail", e);
				});

				// getApp().globalData.chatSocket.send({
				// 	data: JSON.stringify({
				// 		"receiveid": this.id * 1,
				// 		"content": content + '',
				// 		"classify": classify,
				// 		// "nickname": this.user.name,
				// 		// "logo": this.user.logo
				// 	}),
				// 	success: res => {
				// 		console.log('发送成功', res)
				// 		uni.hideLoading()
				// 		// let pages = getCurrentPages(); //获取所有页面栈实例列表
				// 		// let nowPage = pages[pages.length - 1]; //当前页页面实例
				// 		// let prevPage = pages[pages.length - 2]; //上一页页面实例
				// 		// prevPage.$vm.refreshflag = true
				// 		uni.navigateBack()
				// 	},
				// 	fail: (err) => {
				// 		console.log('发送失败', err)
				// 		this.reConnect(content, classify)
				// 	}
				// });
			},
			reConnect(content, classify) {
				setTimeout(() => {
					if (this.reconnectcount < 10) {
						this.reconnectcount++
						this.sendMessage(content, classify)
					} else {
						this.reconnectcount = 0
						uni.showToast({
							title: '发送消息失败',
							icon: 'none'
						})
					}
				}, 500)
			},
		}
	}
</script>

<style lang="scss" scoped>
	.content {
		font-family: PingFang, PingFang SC;
	}

	.top-box {
		width: 100%;
		font-size: 28rpx;
		padding: 20rpx 20rpx;
		box-sizing: border-box;
		color: #5d5e5e;
		border-bottom: #f7f7fb solid 10rpx;
	}

	.one-goods {
		padding: 32rpx 32rpx;
		border-bottom: #f1f1f1 solid 1px;

		.goods-img {
			width: 120rpx;
			height: 120rpx;
			border-radius: 10rpx;
		}

		.goods-info {
			width: calc(100% - 140rpx);
		}

		.changjia {
			font-size: 24rpx;
			line-height: 40rpx;
			color: #9d9fa1;
		}

		.price {
			font-size: 32rpx;
			color: #fc1f10;
			font-weight: bold;
		}

		.add-box,
		.add-box-minus {
			width: 50rpx;
			height: 50rpx;
			border-radius: 10rpx;
		}

		.add-box-minus {
			border: #00b6b2 solid 1px;
			background: #fff;
		}

		.goods-num {
			width: 120rpx;
			font-size: 28rpx;
			text-align: center;
		}
	}

	.submit-box {
		position: fixed;
		bottom: 0;
		background: #fff;
		padding: 20rpx 40rpx;
		border-top: #f1f1f1 solid 1px;
		padding-bottom: 40rpx;
	}

	.totalPrice {
		font-size: 28rpx;

		text {
			margin-left: 20rpx;
			font-size: 40rpx;
			color: #ff2917;
			font-weight: bold;
		}
	}

	.submit-btn {
		border-radius: 10rpx;
		width: 300rpx;
		height: 90rpx;
		color: #fff;
		font-size: 28rpx;
	}
</style>